package com.uw.scenic.config.gateway.filter;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 限流过滤器
 * 对Ip限流扩展https://blog.csdn.net/weixin_45730091/article/details/103063056
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class RatelimiterFilter extends  AbstractPreZuulFilter{

    /**2.0-->每秒可以获取到两个令牌***/
    RateLimiter rateLimiter=RateLimiter.create(2.0);

    @Override
    protected Object cRun() {
        HttpServletRequest request=context.getRequest();
        if(rateLimiter.tryAcquire()){
            //成功获取了令牌
            log.info("get rate token success");
            return success();
        }else{
            log.error(String.format("%s request to %s"),request.getMethod(),request.getRequestURL().toString());
            return fail(402,"error:rate limit");
        }
    }

    @Override
    public int filterOrder() {
        return 2;
    }
}
